from django.contrib import auth
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response

from sqtp.models import User
from sqtp.serializers import UserSerializer, RegisterSerializer, LoginSerializer


@api_view(['GET'])
def user_list(request):
    queryset = User.objects.all()
    serializer = UserSerializer(queryset, many=True)
    return Response(serializer.data)


@api_view(['GET'])
def user_detail(request, pk):
    try:
        queryset = User.objects.get(pk=pk)
    except Exception as e:
        return Response(status=status.HTTP_404_NOT_FOUND)
    serializer = UserSerializer(queryset)
    return Response(serializer.data)


@api_view(['POST'])
# @permission_classes([])
def register(request):
    serializer = RegisterSerializer(data=request.data)
    if serializer.is_valid():
        user = serializer.register()
        # 完成用户登录状态设置
        auth.login(request, user)
        return Response(
            status=status.HTTP_201_CREATED,
            data={
                'msg': '用户注册成功',
                'is_admin': user.is_superuser,
                'retcode': status.HTTP_201_CREATED
            }
        )
    return Response(
        data={
            'msg': 'error',
            'retcode': status.HTTP_400_BAD_REQUEST,
            'error': serializer.errors
        },
        status=status.HTTP_400_BAD_REQUEST
    )


# 登录
@api_view(['POST'])
# @permission_classes([])
def login(request):
    serializer = LoginSerializer(data=request.data)
    user = serializer.validate(request.data)
    if user:
        auth.login(request, user)
        return Response(
            status=status.HTTP_302_FOUND,
            data={
                'msg': '用户登录成功',
                'retcode': status.HTTP_302_FOUND,
                'to': 'index.html'
            }
        )
    return Response(
        status=status.HTTP_400_BAD_REQUEST,
        data={
            'msg': 'error',
            'retcode': status.HTTP_400_BAD_REQUEST,
            'error': serializer.errors
        }
    )


# 登出
@api_view(['GET'])
# @permission_classes([])
def logout(request):
    if request.user.is_authenticated:
        auth.logout(request)  # 清除登录信息
        print("清楚用户信息")
    return Response(
        status=status.HTTP_302_FOUND,
        data={
            'msg': '用户退出登录成功',
            'retcode': status.HTTP_302_FOUND,
            'to': 'login.html'
        }
    )


# 获取当前用户信息视图
@api_view(['GET'])
# @permission_classes([])
def current_user(request):
    if request.user.is_authenticated:
        serializer = UserSerializer(request.user)
        return Response(data=serializer.data)
    else:
        return Response(
            status=status.HTTP_403_FORBIDDEN,
            data={
                'msg': '您未登录',
                'to': 'login.html',
                'retcode': status.HTTP_403_FORBIDDEN
            }
        )
